/* global window */
import modelExtend from 'dva-model-extend'
import queryString from 'query-string'
import { list, add, edit, del } from 'services/entityDirector'
import { message } from 'antd'
import pathToRegexp from 'path-to-regexp'
import * as basicData from 'services/basicData.js'
import { pageModel } from './common'

export default modelExtend(pageModel, {
  namespace: 'entityDirector',
  state: {
    entityId: '',
    roleOptions: [],
  },
  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((pathname) => {
        const match = pathToRegexp('/entitydirector/:id').exec(pathname.pathname)
        if (match) {
          dispatch({
            type: 'list',
            payload: {
              id: match[1],
            },
          })
          dispatch({ type: 'iniBasicData' })
          dispatch({
            type: 'updateState',
            payload: {
              entityId: match[1],
            },
          })
        }
      })
    },
  },
  effects: {
    * list ({ payload }, { call, put }) {
      const data = yield call(list, payload)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            data: data.data,
          },
        })
      }
    },
    * delete ({ payload }, { call, put, select }) {
      const data = yield call(del, payload)
      if (data.success) {
        message.success('delete success')
      } else {
        message.error('delete failed')
      }
    },
    * iniBasicData ({ payload = {} }, { call, put }) {
      const roleOptions = yield call(basicData.list, { type: 'EntityPersonRoleType', page: 1 })
      if (roleOptions.success) {
        yield put({
          type: 'updateState',
          payload: {
            roleOptions: roleOptions.data.data,
          },
        })
      }
    },
  },

  reducers: {

  },
})
